package com.pay.util;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;

import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisSentinelPool;

public class EnhanceJedisSentinelPool extends JedisSentinelPool {
    private Set<HostAndPort> sentinelHostAndPort;
    private static String splitChar = "[,;]";
    public EnhanceJedisSentinelPool(String masterName, String sentinels, final GenericObjectPoolConfig poolConfig, int timeout, final String password, final int database) {
        super(masterName, sentinelsStringToSet(sentinels), poolConfig, timeout,  password, database);
        sentinelHostAndPort = toHostAndPortSet(sentinels);
    }

    public EnhanceJedisSentinelPool(String masterName, String sentinels, final GenericObjectPoolConfig poolConfig, int timeout, final int database) {
        super(masterName, sentinelsStringToSet(sentinels), poolConfig, timeout,  null, database);
        sentinelHostAndPort = toHostAndPortSet(sentinels);
    }

    private static Set<String> sentinelsStringToSet(String sentinels) {
        return new HashSet<String>(Arrays.asList(sentinels.split(splitChar)));
    }

    private static Set<HostAndPort> toHostAndPortSet(String sentinels) {
        Set<HostAndPort> set = new HashSet<HostAndPort>();
        String[] hostAndPortArray = sentinels.split(splitChar);
        for(String hostAndPortStr : hostAndPortArray) {
            String[] hostAndPortArr =  hostAndPortStr.split(":");
            set.add(new HostAndPort(hostAndPortArr[0], Integer.valueOf(hostAndPortArr[1])));
        }
        return set;
    }

    public Set<HostAndPort> getSentinelHostAndPort() {
        return sentinelHostAndPort;
    }

    @SuppressWarnings("rawtypes")
    public GenericObjectPool getInternalObjectPool() {
        return this.internalPool;
    }
}
